// Edit in place
// Bits lifted from inlineeditor.js
// See http://iharder.sourceforge.net/current/misc/inlineeditor/index.html
// Requires jQuery 1.1

EditInPlace = {

	start: function(target, callbackFn, id) {

        // If element is "uneditable" or "editing" don't edit.
        // if (Element.hasClassName(target, 'editing'))
        //    return;

		if (!target) {
			alert("Attempting to edit empty node with id: " + id);
			return;
		}

		if (target.hasClass("editing")) {
			alert("Info: target already has class 'editing'.");
			return;
		}

        // Save original value.
        var oldHTML = target.html();
        var oldVal = target.html();

        var editor = $("<input class='editor'>");
        editor.val(oldVal);
		editor.css({
			position: "absolute", 
			zindex: "99", 
			width: target.width() + "px"
		});
		
        // Listen for when focus is lost or CR is pressed
        editor.blur(function () { 
			EditInPlace.stop(editor, oldVal, oldHTML, callbackFn, id); 
		});

		editor.keypress(function (e) {
			if (e.keyCode == 13)
				EditInPlace.stop(editor, oldVal, oldHTML, callbackFn, id);
		});

        // Element.addClassName( target, 'editing' );
		target.addClass("editing");

        // Add editor
        // target.html("");
        target.prepend(editor);
        editor.focus();
    },


    /**
     * Called when user is done editing the cell.
     */
    stop: function(editor, oldVal, oldHTML, callbackFn, id)
    {
        // Gather values
        var parent = editor.parent();
        var newVal = null;
		newVal = editor.val() ? editor.val() : editor.html(); // Fallback      
            
        // If nothing changed, bail out
        if( oldVal == newVal ){
            parent.html(oldHTML);
            // Element.removeClassName(parent, 'editing');
			parent.removeClass("editing");
            return;
        }   // end if: no change

        // Save value in the element
        parent.html(newVal);
        // Element.removeClassName(parent, 'editing');
		parent.removeClass("editing");
		callbackFn(id, newVal);
    }
}

// The End
